import { addMockData, deleteMockData, getKeyName, getMockData, updateMockData } from "@/api";
import { CodeObject, DataBase as DB, TableObject } from "@/type/global";
import React, { useEffect, useState } from "react"
import { Alert, Input, Card, Button, Badge, message, Drawer, Spin, Modal } from 'antd';
import { ProList } from "@ant-design/pro-components";
import { CopyOutlined, ExclamationCircleOutlined, EyeOutlined } from '@ant-design/icons';
import { copyCode } from "@/common/utils";
import DataBaseForm from '@/components/DataBaseForm';
import { generateCode } from "@/common/generateCode";
import CodeView from "@/components/CodeView";
const { TextArea } = Input;
const DataBase: React.FC = () => {
    const [dataBaseList, setDataBaseList] = useState<DB[]>();
    const [visible, setVisible] = useState(false);
    const [currentData, setCurrentData] = useState<DB>();
    const [drawerVisible, setDrawerVisible] = useState(false);
    const [code, setCode] = useState<CodeObject>();
    const [loading, setLoading] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const [modalType, setModalType] = useState<'post' | 'put'>('post');
    const [currentView, setCurrentView] = useState('');
    useEffect(() => {
        getKeyName().then(res => {
            setDataBaseList(res);
        })
    }, []);

    function handleClose() {
        setVisible(false);
        setCurrentData(void 0);
    }

    function handleOk(value: DB) {
        if (!value.key || !value.desc || !value.data) return message.error('请填写完整的信息');
        const fn = modalType === 'post' ? addMockData : updateMockData;
        fn({
            ...value,
            data: (value.data as unknown as string).split(',')
        }).then(res => {
            localStorage.removeItem(value.key);
            getKeyName().then(res => {
                setDataBaseList(res);
                setVisible(false);
            })
        })
    }

    function handleShowUpdate(type: 'put' | 'post', data?: DB) {
        setModalType(type);
        if (data) setCurrentData(data);
        setVisible(true);
    }

    async function handleOpenDrawer(row: DB) {
        let obj: TableObject = {
            tableName: 'test_table',
            tableComment: '表格描述',
            fieldList: [
                { fieldName: row.key, mockType: row.key, comment: row.desc }
            ]
        }
        setLoading(true);
        const codeResult = await generateCode(obj);
        setLoading(false);
        setCode(codeResult);

        setDrawerVisible(true);
    }

    function handleViewData(text: string[]) {
        setCurrentView(text.join(','));
        setModalVisible(true);
    }

    function handleDelete(row: DB) {
        Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined />,
            content: '是否删除此映射数据',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                deleteMockData(row.id!).then(res => {
                    localStorage.removeItem(row.key);
                    getKeyName().then(res => {
                        setDataBaseList(res);
                    })
                });
            }
        })

    }


    return <div>
        <DataBaseForm visible={visible} onOk={handleOk} currentData={currentData} onClose={handleClose}></DataBaseForm>
        <Alert style={{ marginTop: '12px' }} message="可配置自己的数据，映射到模拟数据池中。" type="warning" />
        <Drawer width={800} onClose={() => setDrawerVisible(false)} open={drawerVisible} title="代码生成">
            {code && <CodeView code={code}></CodeView>}
        </Drawer>
        <Modal footer={null} onCancel={() => setModalVisible(false)} title="查看数据" open={modalVisible}>
            <TextArea value={currentView} disabled />
        </Modal>
        <Spin spinning={loading} tip="生成数据中，请稍后...">
            <ProList<DB>
                rowKey="key"
                dataSource={dataBaseList}
                metas={{
                    title: {
                        dataIndex: 'key',
                    },
                    description: {
                        dataIndex: 'desc',
                        render: (text) => (
                            <div>
                                {text || '暂未配置'}
                            </div>
                        )
                    },
                    content: {
                        dataIndex: 'data',
                        render: (text) => (
                            (text && <div>

                                <div style={{ color: '#000000' }}>数据</div>
                                <div key="key" style={{ display: 'flex' }}>
                                    {(text as any[]).map((t, index) => (
                                        index <= 8 && (<div key={index} style={{ color: '#00000073' }}>
                                            {JSON.stringify(t)}
                                        </div>)
                                    ))}
                                    <div>
                                        <Button onClick={(e) => copyCode(e, (text as string[]).join(','))} size="small" style={{ marginLeft: '8px' }} icon={<CopyOutlined />}></Button>
                                        <Button onClick={(e) => handleViewData(text as string[])} size="small" style={{ marginLeft: '8px' }} icon={<EyeOutlined />}></Button>

                                    </div>
                                </div>
                            </div>)
                        ),
                    },

                    actions: {
                        render: (text, row) => [
                            <a onClick={() => handleOpenDrawer(row)} rel="noopener noreferrer" key="generate">
                                生成
                            </a>,
                            <a onClick={() => handleShowUpdate('put', row)} rel="noopener noreferrer" key="link">
                                编辑
                            </a>,
                            <a onClick={() => handleDelete(row)} key="view">
                                删除
                            </a>,
                        ],
                    },
                }}
                toolbar={{
                    menu: {
                        items: [
                            {
                                key: 'tab1',
                                label: <span>数据池{<Badge
                                    count={dataBaseList?.length}
                                    style={{
                                        marginBlockStart: -2,
                                        marginInlineStart: 4,
                                        color: '#1890FF',
                                        backgroundColor: '#E6F7FF',
                                    }}
                                />}</span>,
                            },
                        ],
                    },
                    search: {
                        onSearch: (value: string) => {
                            getMockData(value).then(res => {
                                setDataBaseList(res);
                            })
                        },
                    },
                    actions: [
                        <Button onClick={() => handleShowUpdate('post')} type="primary" key="primary">
                            新建数据
                        </Button>,
                    ],

                }}
            />
        </Spin>

    </div>
}

export default DataBase;

